/**
 * 
 */
package org.braketester.model.filters;

import java.util.ArrayList;
import java.util.concurrent.LinkedBlockingQueue;

import org.braketester.entry.ExceptionResolver;
/**
 * @author LAP
 *
 */
public abstract class RunnableFilter implements Runnable {
	private ArrayList<RunnableFilter> nextFiltersList;
	private LinkedBlockingQueue<Double> valuesQueue;
	
	public RunnableFilter() {
		this(new ArrayList<RunnableFilter>());
	}
	
	public RunnableFilter(RunnableFilter nextFilter) {
		this(new ArrayList<RunnableFilter>());
		if (nextFilter == null) throw new NullPointerException("Filter must be not null");
		nextFiltersList.add(nextFilter);
	}
	
	public RunnableFilter(ArrayList<RunnableFilter> nextFiltersList) {
		if (nextFiltersList == null) this.nextFiltersList = new ArrayList<RunnableFilter>();
		else this.nextFiltersList = nextFiltersList;
		valuesQueue = new LinkedBlockingQueue<Double>();
	}
	
	public void addValue(Double value) {
		tryPutValue(value);
	}
	
	private void tryPutValue(Double value) {
		try {
			valuesQueue.put(value);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public void addNextFilter(RunnableFilter filter) {
		nextFiltersList.add(filter);
	}
	
	private void fireValue(Double value) {
		for(RunnableFilter filter : nextFiltersList) filter.addValue(value);
	}
	
	@Override
	public void run() {
		while(true) {
			Double value = tryTakeValue();
			value = doFilter(value);
			if (!nextFiltersList.isEmpty()) fireValue(value);
		}
	}
	
	private Double tryTakeValue() {
		Double value = null;
		try {
			value = valuesQueue.take();
		} catch (InterruptedException e) {
			ExceptionResolver.getInstance().logException(e);
			ExceptionResolver.getInstance().showException(e);
		}
		return value;
	}
	
	abstract protected Double doFilter(Double value);
	
	public void start() {
		for(RunnableFilter filter : nextFiltersList) {
			filter.start();
		}
	}
}
